package cn.hd.authorService.service.author.impl;

import cn.hd.authorService.service.user.UserService;
import cn.hd.authorService.vo.LoginUser;
import cn.hd.commonService.entity.SysUser;
import cn.hd.commonService.vo.function.FunctionAuthorityVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.getUserByAccount(username).getData();
        //查询权限信息
        List<FunctionAuthorityVo> list = userService.getAuthorityListByUserId(user.getRecordId()).getData();
        //元素去重
        list=  list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(FunctionAuthorityVo::getRecordId))), ArrayList::new));
        //把数据封装成UserDetails返回
        return new LoginUser(user,list);
    }
}
